package com.minelx.statementsplus.cha.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import static java.nio.charset.StandardCharsets.UTF_8;

public class ActualResponseFetcher {

	private final ChaRequestMapper chaRequestMapper;

	private final String sessionId;

	private final String secretKey;

	private final TaskCommitment commitment;

	private long downloadNumber;

	private long bval;

	public ActualResponseFetcher(ChaRequestMapper chaRequestMapper,
								 String sessionId,
								 String secretKey,
								 TaskCommitment commitment) {
		this.chaRequestMapper = chaRequestMapper;
		this.sessionId = sessionId;
		this.secretKey = secretKey;
		this.commitment = commitment;
		downloadNumber = 0;
		bval = -1;
	}

	JSONObject next() {
		JSONObject result = JSON.parseObject(fetchTextOfResponseAt(bval));
		// update bval
		bval = DoWorkResponse.from(result).bval();
		// push download number
		downloadNumber += result.getIntValue("ttl");
		return result;
	}

	private String fetchTextOfResponseAt(long bval) {
		return chaRequestMapper.requestDoWork(sessionId,
				secretKey,
				commitment,
				downloadNumber,
				bval,
				1).contentAsText(UTF_8);
	}
}

